<?php

namespace app\store\controller;

use think\Request;
use app\store\model\UserRecordInfo as UserRecordInfoModel;
use app\store\model\UserJob;
use app\store\model\UserFamilyInfo;

class UserRecordInfo extends Controller
{
    public $model;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->model = new UserRecordInfoModel();
    }

    /**
     * 列表
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function index(){
        $param = $this->request->param();
        $list = $this->model->getList($param);
        return show(self::SUCCESS,'操作成功',$list);
    }

    /**
     * 添加
     * @return \think\response\Json
     */
    public function add(){
        //
        $jobModel = new UserJob();
        $familyModel = new UserFamilyInfo();
        $record_json = $this->request->param();
        $action = $this->request->get('action');
        if(!empty($action) && $action=='edit'){
            $user_id = $this->request->get('user_id');
            $detail = $this->model->detail($user_id);
            if($detail){
                return show(self::SUCCESS,'操作成功',$detail);
            }else{
                return show(self::SUCCESS,'操作成功');
            }
        }
        unset($record_json['action']);
        $jobs_json = htmlspecialchars_decode($this->request->param('job'));
        $family_json = htmlspecialchars_decode($this->request->param('family'));
        if(!empty($jobs_json)){
            $job = json_decode($jobs_json,true);
            unset($record_json['job']);
        }
        if(!empty($family_json)){
            $family = json_decode($family_json,true);
            unset($record_json['family']);
        }
        if(!empty($record_json['id'])){
            $detailinfo = $this->model->details($record_json['id']);
            $id = $record_json['id'];
            unset($record_json['id']);
            $result = $detailinfo->edit($record_json,['id'=>$id]);
            $record_json['record_id'] = $id;
        }else{
            $result = $this->model->add($record_json);
            $record_json['record_id'] = $this->model->id;
        }
        //var_dump($record_json);exit();
        //$result = $this->model->add($record_json);
        // $record_json['record_id'] = $this->model->id;
        if(!empty($job)){
            $jobModel->add($job,$record_json);
        }
        if(!empty($family)){
            $familyModel->add($family,$record_json);
        }
        if($result){
            return show(self::SUCCESS,'操作成功');
        }
        return show(self::ERROR,'操作失败');
    }
}